import React, { useRef, useState } from 'react';
import ProTable from '@ant-design/pro-table';
import { Button, Avatar, Switch, message, Space, Popconfirm } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined, UserOutlined } from '@ant-design/icons';
import { getMemberList, disable, delUser } from '@/services/user';
import Edit from './components/Edit';

const Index = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editId, setEditId] = useState(undefined);
  const [userLockId, setUserLockId] = useState(0);

  const actionRef = useRef();

  /**
   * 获取数据
   * 作者：糜家智
   * 时间：2021/8/2 18:03
   */
  const getData = async (params, sort) => {

    const { current, pageSize, ...paramsData } = params

    // 取出排序的key值
    let sortKey = Object.getOwnPropertyNames(sort)
    let sortData = {
      sort_field: sortKey,
      // 判断是否有key值
      sort_type: sortKey == false ? [] : (sort[sortKey] === 'ascend' ? 'asc' : 'desc')
    }

    const res = await getMemberList({
      page: params.current,
      limit: params.pageSize,
      ...paramsData,
      ...sortData
    });

    return {
      data: res.data.list,
      success: true,
      total: res.data.count,
    };
  };

  /**
   * 用户的启用和禁用
   * @param {*} uid
   */
  const handleUserLock = async (uid, key) => {
    setUserLockId(uid);
    const setId = key === 0 ? 1 : 0;

    const res = await disable({ member_id: uid, is_disable: setId });
    if (res.code === 200) {
      message.success(res.msg);
    }
    setUserLockId(0);
  };

  /**
   * 删除列
   * @param id
   * @returns {Promise<void>}
   */
  const handleDel = async (id) => {
    const res = await delUser({
      member_id: id,
    });
    if (res.code === 200) {
      actionRef.current?.reload();
      message.success(res.msg);
    }
  };

  /**
   * 模态框的显示和隐藏
   */
  const isShowModal = (show, member_id = null) => {
    setEditId(member_id);
    setIsModalVisible(show);
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 60,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      render: (_, record) => <Avatar size={32} src={record.avatar} icon={<UserOutlined />} />,
      hideInSearch: true,
    },
    {
      title: '账号',
      dataIndex: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      hideInSearch: true,
    },
    {
      title: '手机',
      dataIndex: 'phone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },

    {
      title: '登录时间',
      dataIndex: 'login_time',
      hideInSearch: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '禁用',
      dataIndex: 'is_disable',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_disable === 1}
          loading={record.member_id === userLockId}
          onChange={async () => handleUserLock(record.member_id, record.is_disable)}
        />
      ),
      hideInSearch: true,
    },
    {
      title: '操作',
      // render: (_, record) => <a onClick={() => isShowModal(true, record)}>编辑</a>,
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => isShowModal(true, record.member_id)}>编辑</a>
          <Popconfirm
            title="确定删除吗？"
            onConfirm={() => {
              handleDel(record.member_id);
            }}
            okText="确定"
            cancelText="取消"
          >
            <a href={'javascript'}>删除</a>
          </Popconfirm>
        </Space>
      ),
      hideInSearch: true,
    },
  ];

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={(params, sort) => getData(params, sort)}
        editable={{
          type: 'multiple',
        }}
        rowKey="member_id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="会员列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => isShowModal(true)}
          >
            新建
          </Button>,
        ]}
      />
      {!isModalVisible ? (
        ''
      ) : (
        <Edit
          isModalVisible={isModalVisible}
          isShowModal={isShowModal}
          actionRef={actionRef}
          editId={editId}
        />
      )}
    </PageContainer>
  );
};

export default Index;
